package com.wh1200.mybatis.xmlless.model


/**
 *
 * Created by 吴昊 on 2018-12-09.
 *
 * @author 吴昊
 * @since 0.0.1
 */
data class ResolvedQuery(
    val query: Query? = null,
    /** 待解析的方法 */
    val methodInfo: MethodInfo,
    val exception: Exception? = null
) {

  /**  sql语句 */
  val sql: String? = query?.toSql()?.let {
    "<script>\n${it.trim()}\n</script>"
  }

  /**  sql类型 */
  val type = query?.type

  override fun toString(): String {
    val sb = StringBuilder()
    sb.append(
        "   ${
          if (isValid()) {
            "已解析"
          } else {
            "未成功解析"
          }
        } 方法:\t${methodInfo.fullMethodName}\n"
    )
    if (isValid()) {
      val prefix = "\t\t- "
      sb.append(prefix).append("类型: $type\n")
      sb.append(prefix).append("SQL: \n${sql!!.trim().indent(5)}\n")
      sb.append(prefix).append("返回: ${methodInfo.returnType}")
    } else {
      sb.append("\t\t - ${exception?.message}")
    }
    sb.append("\n\n")
    return sb.toString()
  }

  private fun isValid(): Boolean {
    return query != null && exception == null
  }

}
